package userdao

import (
	"itodo/core/dao/table"
	"itodo/core/service/common"

	// "itodo/core/util/structutil"
	// "itodo/core/util/timeutil"
	"strconv"

	"github.com/RocksonZeta/wrap/redised"
	"github.com/RocksonZeta/wrap/utils/sutil"
	"github.com/RocksonZeta/wrap/utils/timeutil"
)

type UserPrivates struct {
	*redised.RedisedMysql
}

func (s UserPrivates) redisKey(id int) string {
	return "UserPrivate/" + strconv.Itoa(id)
}

func (s UserPrivates) ClearCache(id int) {
	s.Redis.Del(s.redisKey(id))
}

type UserPrivatesQueryParam struct {
	common.Page
	Name string
}

//Query 根据条件查询
func (s UserPrivates) Query(param UserPrivatesQueryParam) ([]table.UserPrivate, int64) {
	wsql := " from UserPrivate where 1=1"
	if param.Name != "" {
		param.Name = "%" + param.Name + "%"
		wsql += " and name like :Name"
	}
	ssql := "select *" + wsql + " order by ct desc" + param.Limit()
	csql := "select count(*)" + wsql
	var r []table.UserPrivate
	s.Mysql.Select(&r, ssql, param)
	return r, s.Mysql.SelectInt(csql, param)
}

func (s UserPrivates) Get(id int) table.UserPrivate {
	var r table.UserPrivate
	s.RedisedMysql.Get(&r, "UserPrivate", "Id", id)
	return r
}
func (s UserPrivates) GetByEmail(email string) table.UserPrivate {
	var r table.UserPrivate
	s.RedisedMysql.GetByKvs(&r, "UserPrivate", "Id", sutil.M{"email": email})
	return r
}

func (s UserPrivates) List(ids []int) []table.UserPrivate {
	var r []table.UserPrivate
	s.RedisedMysql.List(&r, "UserPrivate", "Id", ids)
	return r
}

type UserPrivatesAddParam struct {
	Name string
}

func (s UserPrivates) Add(param UserPrivatesAddParam) table.UserPrivate {
	var t table.UserPrivate
	sutil.Copy(param, &t)
	t.Ct = timeutil.Now()
	s.Mysql.AddTable(t)
	s.Mysql.Insert(&t)
	s.ClearCache(t.Id)
	return t
}

type UserPrivatesUpdateParam struct {
	Id   int
	Name string
}

func (s UserPrivates) Update(param UserPrivatesUpdateParam) {
	s.Mysql.Patch("UserPrivate", "Id", param)
	s.ClearCache(param.Id)
}

func (s UserPrivates) Delete(id int) {
	s.Mysql.Delete("UserPrivate", "Id", id)
	s.ClearCache(id)
}
